/**
 * 不用 redux-react 的例子
 */

import React from 'react';
import ReactDom from 'react-dom';
import { createStore } from 'redux';

let add = function(txt) {
    return {
        type: "addxxoo",
        txt: txt
    }
}

let reducer = function(state = { items: [] }, action) {
    if (action.type == "addxxoo") {
        return Object.assign({}, state, { items: [...state.items, action.txt] });
    }
    return state;
}

let store = createStore(reducer);

let App = React.createClass({
    getInitialState: function() {
        return {
            items: store.getState().items
        }
    },
    componentDidMount: function() {
        console.dir("componentDidMount");
        var unsubscribe = store.subscribe(this.onChange);
    },
    onChange: function() {
        this.setState({
            items: store.getState().items
        });
    },
    handleAdd: function() {
        var imput = this.refs.todo;
        var value = imput.value.trim();
        if (value) {
            store.dispatch(add(value));
        }
        value = "";
        this.refs.todo.value="";
    },

    render: function() {
        return (
            <div>
                <input ref="todo" type="text" placeholder="输入todo项" style={{ marginRight: '10px' }} />
                <button onClick={this.handleAdd}>点击添加</button>
                <ul>
                    {this.state.items.map(function(item,index) {
                        return <li key={index}>{item}</li>;
                    })}
                </ul>
            </div>
        );
    }
});

ReactDom.render(<App />, document.getElementById("root"));